package com.doubao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.doubao.entity.SOfferlineMsg;
import com.doubao.mapper.SOfferlineMsgMapper;
import com.doubao.protocol.Msg;
import com.doubao.service.ISOfferlineMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author sult
 * @since 2018-11-02
 */
@Service
public class SOfferlineMsgServiceImpl extends ServiceImpl<SOfferlineMsgMapper, SOfferlineMsg> implements ISOfferlineMsgService {

    @Autowired
    private SOfferlineMsgMapper sOfferlineMsgMapper;

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    public List<SOfferlineMsg> getOfferlineMsg(String from, String to) throws Exception {
        Wrapper<SOfferlineMsg> wrapper = new EntityWrapper<>();
        wrapper.eq("to_id", to).eq("from_id",from).eq("state",1).orderBy("ct",true);
        List<SOfferlineMsg> list = sOfferlineMsgMapper.selectList(wrapper);
        for(SOfferlineMsg s:list){
            s.setState(2);
            sOfferlineMsgMapper.updateById(s);
        }
        return list;
    }

    @Override
    @Transactional
    public void saveOfferLineMsg(Msg msg) throws Exception {
        SOfferlineMsg offerlineMsg = new SOfferlineMsg();
        offerlineMsg.setToId(msg.getTo());
        offerlineMsg.setFromId(msg.getFrom());
        offerlineMsg.setCt(new Date(msg.getCt()));
        offerlineMsg.setContent(JSON.toJSONString(msg));

        sOfferlineMsgMapper.insert(offerlineMsg);

    }


}
